### PACKAGE PREAMBLE ###

# Create a vector of package names
packages <- c("dplyr", "ggplot2", "tidyr", "tidyverse", "data.table", "readxl", "foreign", "devtools", "fixest", "sandwich", "modelsummary", "kableExtra")

installed_packages <- packages %in% rownames(installed.packages())
if (any(installed_packages == FALSE)) {
  install.packages(packages[!installed_packages])
}

# Packages loading
invisible(lapply(packages, library, character.only = TRUE))
rm(packages, installed_packages)

options(modelsummary_format_numeric_latex = "plain")
f <- function(x) format(x, digits = 3, nsmall = 2, scientific = FALSE)

getwd()
setwd(dir = "/Users/jmc4qg/The Lab Dropbox/Jonathan Colmer/ShotSpotter_env/Journal_submissions/ReStat/Replication Folder/")

mydata <- read.dta("Analysis Data/NIBRS_analysis.dta")
mydata_LP <- filter(mydata, MP == 0)
mydata_MP <- filter(mydata, MP == 1)

#Table 2: Baseline Temperature--Homicide Relationship

T1 <- feols(homicide_pc~ tMean + prec , data=mydata)
summary(T1, cluster="fips")
T2 <- feols(homicide_pc~ tMean + prec | sample_month + week + dow, data=mydata)
summary(T2, cluster="fips")
T3 <- feols(homicide_pc~ tMean + prec | state_sample_month + week + dow, data=mydata)
summary(T3, cluster="fips")
T4 <- feols(homicide_pc~ tMean + prec | ori_sample_month + week + dow, data=mydata)
summary(T4, cluster="fips")


models <- list(T1, T2, T3, T4)
modelsummary(models, vcov = ~fips, output = "Figures and Tables/Table_2/Panel_A_Table_2.tex", fmt = f, stars = c('*' = 0.1, '**' = 0.05, '***' = 0.01))

T1_MP <- feols(homicide_pc~ tMean + prec, data=mydata_MP)
summary(T1_MP, cluster="fips")
T2_MP <- feols(homicide_pc~ tMean + prec | sample_month + week + dow, data=mydata_MP)
summary(T2_MP, cluster="fips")
T3_MP <- feols(homicide_pc~ tMean + prec | state_sample_month + week + dow, data=mydata_MP)
summary(T3_MP, cluster="fips")
T4_MP <- feols(homicide_pc~ tMean + prec | ori_sample_month + week + dow, data=mydata_MP)
summary(T4_MP, cluster="fips")

models <- list(T1_MP, T2_MP, T3_MP, T4_MP)
modelsummary(models, vcov = ~fips, output = "Figures and Tables/Table_2/Panel_B_Table_2.tex", fmt = f, stars = c('*' = 0.1, '**' = 0.05, '***' = 0.01))

T1_LP <- feols(homicide_pc~ tMean + prec, data=mydata_LP)
summary(T1_LP, cluster="fips")
T2_LP <- feols(homicide_pc~ tMean + prec | sample_month + week + dow, data=mydata_LP)
summary(T2_LP, cluster="fips")
T3_LP <- feols(homicide_pc~ tMean + prec | state_sample_month + week + dow, data=mydata_LP)
summary(T3_LP, cluster="fips")
T4_LP <- feols(homicide_pc~ tMean + prec | ori_sample_month + week + dow, data=mydata_LP)
summary(T4_LP, cluster="fips")

models <- list(T1_LP, T2_LP, T3_LP, T4_LP)
modelsummary(models, vcov = ~fips, output = "Figures and Tables/Table_2/Panel_C_Table_2.tex", fmt = f, stars = c('*' = 0.1, '**' = 0.05, '***' = 0.01))
